<template>
  <el-drawer
    size="90%"
    v-model="dialogVisibled"
    :before-close="handleClose"
    :title="dialogTitle"
    :close-on-click-modal="false"
    @open="handleDialogOpen"
  >
    <el-divider />

    <el-tabs
      v-model="activeName"
      style="
        margin-left: 10px;
        height: 100%;
        min-height: 800px;
        min-width: 1440px;
        overflow: auto;
      "
    >
      <el-tab-pane label="流程基本信息" name="flowBaseMsg">
        <div>
          <div style="padding: 10px">
            <el-form
              ref="ruleFormRef"
              :model="model"
              status-icon
              :rules="rules"
              label-width="auto"
            >
              <el-form-item label="流程名称：" prop="FlowName">
                <el-input
                  v-model="model.FlowName"
                  placeholder="请输入流程名称"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="所属部门：" prop="DepartmentId">
                <el-tree-select
                  placeholder="请选择部门"
                  v-model="model.DepartmentId"
                  :data="departmentList"
                  check-strictly
                  :default-expand-all="true"
                  @change="departmentClick"
                  :render-after-expand="false"
                >
                </el-tree-select>
              </el-form-item>
              <el-form-item label="绑定表单：" prop="FormId">
                <el-tree-select
                  placeholder="请选择表单"
                  v-model="model.FormId"
                  :disabled="!model.DepartmentId"
                  :data="formList"
                  @change="formClick"
                  check-strictly
                  :default-expand-all="true"
                  :render-after-expand="false"
                >
                </el-tree-select>
              </el-form-item>
              <el-form-item label="流程备注：" prop="Remark">
                <el-input
                  clearable
                  v-model="model.Remark"
                  maxlength="200"
                  placeholder="请输入流程备注"
                  show-word-limit
                  type="textarea"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane
        label="设计流程(选择表单后才能设计)"
        name="designerFlow"
        :disabled="!model.FormId"
        style="height: 100%"
      >
        <dawnFlow
          :NodeBar="true"
          :ToolBar="true"
          @currentNodeDoubleClick="nodeClick"
          @currentEdgeDoubleClick="edgeClick"
          ref="uploadFileRef"
        />

        <!-- <div class="opt-style-text1">
          <div>
            <el-tooltip effect="customized">
              <template #content
                >1：按住Ctrl+鼠标左键可多选<br />2：双击鼠标左键可以编辑节点和线条信息
              </template>
              <el-button type="warning" link
                ><el-icon size="18"><QuestionFilled /></el-icon>操作提示</el-button
              >
            </el-tooltip>
          </div>
        </div> -->
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button icon="Close" size="large" type="danger" plain @click="handleClose"
        >取消</el-button
      >
      <el-button type="primary" size="large" icon="Check" plain @click="submitForm"
        >保存流程</el-button
      >
    </template>
  </el-drawer>

  <!-- 普通节点 -->
  <editOrdinaryNodeNode
    :dialog-title="nodeModel.dialogTitle"
    :is-visibles="nodeModel.isVisibles"
    :node-model="nodeModel.nodeData"
    :node-type="nodeModel.nodeType"
    @closeBnt="colosClick"
    @saveNodeClick="returnNodeClcik"
  ></editOrdinaryNodeNode>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, reactive, ref } from "vue";
import { ArrowLeft, Close } from "@element-plus/icons-vue";
import { ElMessage, FormInstance } from "element-plus";
import { GetFormByDepId, GetFormField } from "@/api/form";
import { getDepartmentTree } from "@/api/overallAuthApi";
import { treeOutPut } from "@/model/public/treeModel";
import { FormRules } from "element-plus/es/components/form/src/types";
import { DataStateEnum } from "@/enum/public";
import { FlowModel } from "@/model/flow";
import { GetExpireDate, GetFlowByFlowId, InsertFlow, UpdateFlow } from "@/api/flow";
import editOrdinaryNodeNode from "@/views/templateManage/flowTemplate/editOrdinaryNodeNode.vue";
import { FlowInput, flowNodeModel } from "@/model/flow/flowModel";
import { selectOutPut } from "@/model/public/selectModel";
import {
  ExpireActionEnum,
  FlowNodeTypeEnum,
  NodeCountersignOrderEnum,
  NodeCountersignWayEnum,
} from "@/enum/flowEnum";
import { cloneDeep } from "lodash";
import { getIndexByEnumName } from "@/api/publicTool";
export default defineComponent({
  props: {
    isVisibles: {
      type: Boolean,
    },
    dialogTitle: { type: String },
    flowId: {
      type: String,
      required: true,
    },
  },

  setup(props, context) {
    //#region  初始化和变量
    //tabKey
    const activeName = ref("flowBaseMsg");
    //流程组件ref
    const uploadFileRef = ref();
    //节点配置集合
    const nodeConfigList = ref<flowNodeModel[]>([]);
    //节点模型
    const nodeModel = reactive({
      isVisibles: false,
      dialogTitle: "",
      nodeType: 2,
      nodeData: {} as flowNodeModel,
    });

    //部门数据
    const departmentList = ref<treeOutPut[]>([]);
    //表单数据
    const formList = ref<treeOutPut[]>([]);
    //表单字段集合
    const formFieldList = ref<selectOutPut[]>([]);
    //新增/编辑输入模型
    const flowInput = ref<FlowInput>({
      flowNodeConfigList: [] as any,
      flow: {} as any,
    });
    //模型
    var model = ref<FlowModel>({
      FlowId: "",
      FlowContent: "",
      FormId: "",
      DepartmentId: undefined,
      FlowName: "",
      TypeId: undefined,
      Remark: "",
      DataState: DataStateEnum.Enable,
    });

    //打开时加载
    const handleDialogOpen = function () {
      ClearModel();
      activeName.value = "flowBaseMsg";
      resetForm(ruleFormRef.value);
      formFieldList.value = [];
      formList.value = [];
      departmentList.value = [];
      uploadFileRef.value.delFlowClick();
      getCorporationDepartmentListMsg();
      nodeConfigList.value = [];
      if (props.flowId != "") {
        getFlowByFlowIdMsg();
      }
    };

    //清空模型
    const ClearModel = function () {
      model.value.FlowId = "";
      model.value.FlowContent = "";
      model.value.FormId = "";
      model.value.DepartmentId = undefined;
      model.value.FlowName = "";
      model.value.TypeId = undefined;
      model.value.Remark = "";
      model.value.DataState = DataStateEnum.Enable;
    };

    //#endregion

    //#region  验证规则

    //注册验证
    const ruleFormRef = ref<FormInstance>();
    const rules = reactive<FormRules<typeof model.value>>({
      FlowName: [
        {
          required: true,
          message: "请填写流程名称!",
          trigger: "blur",
        },
      ],
      DepartmentId: [
        {
          required: true,
          message: "请选择所属部门!",
          trigger: "change",
        },
      ],
      FormId: [
        {
          required: true,
          message: "请选择绑定表单!",
          trigger: "change",
        },
      ],
    });
    //清除验证
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    //#endregion

    //#region  事件

    //根据流程id获取流程信息
    const getFlowByFlowIdMsg = function () {
      GetFlowByFlowId({ flowId: props.flowId }).then(({ data, code }) => {
        if (code == 200) {
          //设置数据
          model.value = data;
          uploadFileRef.value.setFlowJson(model.value.FlowContent);
          getFormByDepIdMsg();
          formClick();
        }
      });
    };

    //获取部门数据
    const getCorporationDepartmentListMsg = function () {
      getDepartmentTree().then(({ data, code }) => {
        if (code == 200) {
          departmentList.value = data;
        }
      });
    };

    //部门选择事件
    const departmentClick = function () {
      model.value.FormId = "";
      getFormByDepIdMsg();
    };

    //获取部门key,获取表单
    const getFormByDepIdMsg = function () {
      formList.value=[];
      GetFormByDepId({ departmentId: model.value.DepartmentId }).then(
        ({ data, code }) => {
          if (code == 200) {
            formList.value = data;
          }
        }
      );
    };

    //表单事件
    const formClick = function () {
      formFieldList.value = [];
      GetFormField({ formId: model.value.FormId }).then(({ data, code }) => {
        if (code == 200) {
          formFieldList.value = data;
          //切换表单之后，要重置节点表单字段
          nodeConfigList.value.filter((f) => (f.FormFieldAuth = formFieldList.value));
        }
      });
    };

    //验证表单基本信息
    const verifyFormBaseMsg = async (formEl: FormInstance | undefined) => {
      var isTrue = ref<boolean>();
      if (!formEl) return;
      await formEl.validate((valid) => {
        isTrue.value = valid;
      });
      return isTrue;
    };

    //提交
    const submitForm = async () => {
      const formBaseState = await verifyFormBaseMsg(ruleFormRef.value);
      if (formBaseState?.value) {
        flowInput.value.flowNodeConfigList = [];
        nodeConfigList.value.forEach((item) => {
          flowInput.value.flowNodeConfigList.push({
            FlowId: model.value.FlowId,
            FormId: model.value.FormId,
            Id: item.Id,
            FlowNodeId: item.NodeId,
            NodeType: item.NodeType,
            ExpireConfig: JSON.stringify({
              IsSetExamineExpire: item.IsSetExamineExpire,
              ExpireDate: item.ExpireDate,
              ExpireType:item.ExpireType,
              ExpireAction: item.ExpireAction,
              IsExpireRemind: item.IsExpireRemind,
              SoonExpireDate: item.SoonExpireDate,
              RemindContent: item.RemindContent,
            }),
            IsExpireRemind: item.IsExpireRemind,
            FieldAuthConfig: JSON.stringify(item.FormFieldAuth),
          });
        });

        model.value.FlowContent = uploadFileRef.value?.getFlowJson();
        flowInput.value.flow = model.value;
        if (model.value.FlowId !== "") {
          UpdateFlow(flowInput.value).then(({ code }) => {
            if (code == 200) {
              handleClose();
              ElMessage.success("更新成功");
            }
          });
        } else {
          InsertFlow(flowInput.value).then(({ code }) => {
            if (code == 200) {
              handleClose();
              ElMessage.success("新增成功");
            }
          });
        }
      }
    };

    //是否显示dialog
    const dialogVisibled = computed(() => {
      return props.isVisibles;
    });

    //节点返回事件
    const returnNodeClcik = function (data: flowNodeModel) {
      const isTrue = nodeConfigList.value.some((f) => f.NodeId === data.NodeId);
      if (isTrue) {
        // 根据索引删除
        const index = nodeConfigList.value.findIndex(
          (item) => item.NodeId === data.NodeId
        );
        if (index !== -1) {
          nodeConfigList.value.splice(index, 1);
        }
      }
      nodeConfigList.value.push(data);
      updateNode(data);
    };

    //修改节点数据
    const updateFlowKey = ref(0);
    function updateNode(data: flowNodeModel) {
      const elements = JSON.parse(uploadFileRef.value.getFlowJson());
      elements.nodes.filter(
        (item: {
          id: any;
          data: {
            countersignOrder: number;
            countersignWay: number;
            nodeId: string;
            carbonCopyUser: string[] | undefined;
            reviewerIds: string[] | string;
            label: any;
          };
        }) => {
          if (item.id === data.NodeId.toString()) {
            item.data.reviewerIds = data.ReviewerIds;
            item.data.carbonCopyUser = data.CarbonCopyUser;
            item.data.countersignOrder = data.CountersignOrder;
            item.data.countersignWay = data.CountersignWay;
            item.data.label = data.NodeName;
            item.data.nodeId = data.NodeId;
          }
        }
      );
      nextTick(() => {
        const nodeModeld = elements.nodes.find(
          (item: { id: string }) => item.id === data.NodeId.toString()
        );
        uploadFileRef.value.UpdateFlowNode(data.NodeId.toString(), nodeModeld);
      });
    }

    //关闭事件
    const handleClose = () => {
      context.emit("closeBnt");
    };

    //#endregion

    //#region 流程事件

    const nodeClick = function (model: any) {
      nodeModel.dialogTitle = "设置节点审核信息";
      nodeModel.nodeType = getIndexByEnumName(FlowNodeTypeEnum, model.node.type);
      if (props.flowId === "") {
        copyNodeData(model);
      } else {
        //不存在就查询
        if (
          !nodeConfigList.value.some((f) => f.NodeId === model.node.id) &&
          nodeModel.nodeType !== FlowNodeTypeEnum.input &&
          nodeModel.nodeType !== FlowNodeTypeEnum.output
        ) {
          GetExpireDate({ flowId: props.flowId, flowNodeId: model.node.id }).then(
            ({ data, code }) => {
              if (code == 200) {
                nodeConfigList.value.push({
                  Id: "",
                  CountersignWay: model.node.data.countersignWay,
                  CountersignOrder: model.node.data.countersignOrder,
                  NodeId: model.node.id,
                  NodeName: model.node.data.label,
                  NodeType: nodeModel.nodeType,
                  ReviewerIds: model.node.data.reviewerIds,
                  CarbonCopyUser: model.node.data.carbonCopyUser,
                  FormFieldAuth: data.FieldAuthConfigList,
                  IsSetExamineExpire: data.ExpireDateModel.IsSetExamineExpire,
                  ExpireDate:
                    data.ExpireDateModel.IsSetExamineExpire === false
                      ? ""
                      : data.ExpireDateModel.ExpireDate,
                  ExpireAction: data.ExpireDateModel.ExpireAction,
                  IsExpireRemind: data.ExpireDateModel.IsExpireRemind,
                  SoonExpireDate: data.ExpireDateModel.SoonExpireDate,
                  RemindContent: data.ExpireDateModel.RemindContent,
                  ExpireType: data.ExpireDateModel.ExpireType,
                });
                copyNodeData(model);
              } else {
                copyNodeData(model);
              }
            }
          );
        } else copyNodeData(model);
      }
    };

    //拷贝节点数据
    const copyNodeData = function (model: any) {
      const nodeDataList = cloneDeep(nodeConfigList.value);
      if (nodeDataList.some((f) => f.NodeId === model.node.id)) {
        nodeModel.nodeData = cloneDeep(
          nodeDataList.filter((f) => f.NodeId === model.node.id)[0]
        );
      } else {
        nodeModel.nodeData.NodeName = model.node.data.label;
        nodeModel.nodeData.NodeId = model.node.id;
        nodeModel.nodeData.CarbonCopyUser = undefined;
        nodeModel.nodeData.ReviewerIds = [""];
        nodeModel.nodeData.FormFieldAuth = formFieldList.value;
        nodeModel.nodeData.IsSetExamineExpire = false;
        nodeModel.nodeData.ExpireDate = 1;
        nodeModel.nodeData.ExpireType = 1;
        nodeModel.nodeData.ExpireAction = ExpireActionEnum.NoAction;
        nodeModel.nodeData.IsExpireRemind = false;
        nodeModel.nodeData.SoonExpireDate = 10;
        nodeModel.nodeData.RemindContent = "";
        nodeModel.nodeData.Id = "";
        nodeModel.nodeData.NodeType = nodeModel.nodeType;
        nodeModel.nodeData.CountersignWay = NodeCountersignWayEnum.AllReviewerExamine;
        nodeModel.nodeData.CountersignOrder = NodeCountersignOrderEnum.OrderAsc;
      }
      nodeModel.isVisibles = true;
    };

    //线条事件
    const edgeClick = function () {};

    //关闭弹出层
    const colosClick = function () {
      nodeModel.isVisibles = false;
    };
    //#endregion

    return {
      ArrowLeft,
      Close,
      activeName,
      model,
      rules,
      ruleFormRef,
      dialogVisibled,
      handleClose,
      handleDialogOpen,
      submitForm,
      departmentClick,
      nodeClick,
      edgeClick,
      departmentList,
      formList,
      uploadFileRef,
      nodeModel,
      colosClick,
      formClick,
      returnNodeClcik,
      updateFlowKey,
    };
  },
  components: { editOrdinaryNodeNode },
});
</script>

<style lang="scss" scoped>
.el-header.main-header {
  display: none !important;
}

.el-divider__text.is-left {
  font-size: 20px;
}

.opt-style-text1 {
  font-weight: 700;
  border-right: 1px solid #eee;
  font-size: 12px;
  box-shadow: 0 5px 10px #0000004d;
  background: white;
  position: fixed;
  right: 50px;
  top: 125px;
  height: 20px;
  display: flex;
  height: 30px;
  z-index: 999;
}
.opt-style-text1 > * {
  margin-left: 10px;
  margin-right: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: auto;
  cursor: pointer !important;
}
</style>
